﻿using System;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraNavBar;
using xfsale.domain;
using xfsale.lib;
using DevExpress.XtraTab;
using DevExpress.Utils;
using DevExpress.XtraTab.ViewInfo;

namespace xfsale.ui
{
    public partial class WinMain : XtraForm
    {
        public WinMain()
        {
            InitializeComponent();

            NavBarControl bar = null;
            NavBarGroup group = null;
            NavBarItem item = null;
            BarSubItem mnu = null;
            BarSubItem mnu2 = null;
            BarButtonItem mnu3 = null;
            int i = 0;
            foreach (SysMenuItem menu in App.MenuItems)
            {
                //初始化一级菜单
                if (menu.menuId.Length == 2)
                {
                    i++;

                    //新建NavBar
                    bar = new NavBarControl();
                    bar.Name = menu.menuId;
                    bar.Text = menu.menuCaption;
                    bar.Dock = DockStyle.Fill;
                    bar.Visible = (i == 1);
                    bar.LargeImages = Img16X16;
                    bar.SmallImages = Img8X15;
                    bar.Tag = menu;
                    Splitter.Panel1.Controls.Add(bar);

                    mnu = new BarSubItem();
                    mnu.Name = menu.menuId;
                    mnu.Caption = menu.menuCaption + menu.summary;
                    mnu.Tag = menu;
                    BarTool.AddItem(mnu);

                    BarButtonItem barItem = new BarButtonItem();
                    if (!String.IsNullOrEmpty(menu.menuIcon))
                    {
                        barItem.Glyph = System.Drawing.Image.FromFile("Image/" + menu.menuIcon);
                    }
                    else
                    {
                        barItem.Caption = menu.menuCaption;
                    }
                    barItem.Name = "barItem" + menu.menuId;
                    barItem.Border = BorderStyles.HotFlat;
                    barItem.ButtonStyle = BarButtonStyle.Check;
                    barItem.GroupIndex = 99;
                    barItem.Down = (i == 1);
                    barItem.Tag = bar;
                    barItem.DownChanged += new ItemClickEventHandler(BarItem_DownChanged);
                    BarGroup.LinksPersistInfo.Add(new LinkPersistInfo(barItem, true));
                }

                //初始化二级菜单
                if (menu.menuId.Length == 4)
                {
                    //新建NavBarGroup
                    group = new NavBarGroup();
                    group.Name = menu.menuId;
                    group.Caption = menu.menuCaption;
                    group.GroupStyle = NavBarGroupStyle.SmallIconsList;
                    group.Expanded = true;
                    group.LargeImage = Image.FromFile("Image/shortcuytsitems.gif");
                    //group.LargeImageIndex = 0;
                    //group.SmallImageIndex = -1;
                    group.Tag = menu;
                    bar.Groups.Add(group);

                    mnu2 = new BarSubItem();
                    mnu2.Name = menu.menuId;
                    mnu2.Caption = menu.menuCaption;
                    mnu2.Tag = menu;
                    mnu.AddItem(mnu2);
                }

                //初始化三级菜单
                if (menu.menuId.Length == 6)
                {
                    //新建NavBarGroup
                    item = new NavBarItem();
                    item.Name = menu.menuId;
                    item.Caption = menu.menuCaption;
                    item.LargeImageIndex = -1;
                    item.SmallImageIndex = 0;
                    item.Tag = menu;
                    item.LinkClicked += new NavBarLinkEventHandler(BarItem_LinkClicked);
                    group.ItemLinks.Add(item);

                    mnu3 = new BarButtonItem();
                    mnu3.Name = menu.menuId;
                    mnu3.Caption = menu.menuCaption;
                    mnu3.Tag = menu;
                    mnu3.ItemClick += new ItemClickEventHandler(MenuItem_ItemClick);
                    mnu2.AddItem(mnu3);

                    if (string.IsNullOrEmpty(menu.uiFrame))
                    {
                        item.Enabled = false;
                    }
                }
            }

            LblBranchCode.Caption = App.Global.BranchCode;
            LblOpCode.Caption = App.Global.OpCode + " " + App.Global.OpName;
            LblSysStatus.Caption = App.Global.SysStatusText;
            LblSysWorkDay.Caption = App.Global.SysWorkDay;
            LblSysVersion.Caption = App.Global.SysVersion;
        }

        void BarItem_DownChanged(object sender, ItemClickEventArgs e)
        {
            foreach (BarItemLink link in BarGroup.ItemLinks)
            {
                if (link.Item is BarButtonItem)
                {
                    BarButtonItem barItem = link.Item as BarButtonItem;
                    NavBarControl navBar = barItem.Tag as NavBarControl;
                    navBar.Visible = barItem == e.Item;
                }
            }
        }

        void MenuItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            SysMenuItem menu = (e.Item as BarButtonItem).Tag as SysMenuItem;
            ClickMenuItem(menu);
        }


        void BarItem_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            SysMenuItem menu = (sender as NavBarItem).Tag as SysMenuItem;
            ClickMenuItem(menu);
        }

        void ClickMenuItem(SysMenuItem menu)
        {
            if (string.IsNullOrEmpty(menu.uiFrame))
                return;

            try
            {
                //Splitter.Panel1.Enabled = false;
                //if (Splitter.Panel2.Controls.Count > 0)
                //    return;

                /*foreach (Control ctrl in Splitter.Panel2.Controls)
                {
                    ctrl.Dispose();
                }
                Splitter.Panel2.Controls.Clear();*/
                /*NavBarControl NavBar = (Splitter.Panel1.Controls[0] as NavBarControl);
                foreach(NavBarGroup group in NavBar.Groups)
                {
                    foreach(NavBarItemLink item in group.VisibleItemLinks)
                    {
                        item.Item.Enabled = false;
                    }
                }*/

                if (!App.Customer.Identified && menu.uiIdentify == "1")
                {
                    WinIdentify win = new WinIdentify();
                    DialogResult result = win.ShowDialog(this);
                    if (result != DialogResult.OK)
                    {
                        return;
                    }
                }

                string dll = null;
                if (!string.IsNullOrEmpty(menu.uiDll))
                    dll = menu.uiDll;
                FrmBase frame = Activator.CreateInstance(dll, menu.uiFrame).Unwrap() as FrmBase;
                frame.Name = menu.menuId;
                frame.Tag = menu;
                frame.Dock = DockStyle.Fill;


                XtraTabPage tab = null;
                foreach (XtraTabPage t in TabMain.TabPages)
                {
                    if (t.Tag == menu)
                    {
                        tab = t;
                        break;
                    }
                }
                if (tab == null)
                {
                    tab = new XtraTabPage();
                    tab.Text = menu.menuCaption;
                    tab.Tag = menu;
                    tab.ShowCloseButton = DefaultBoolean.True;
                    tab.Controls.Add(frame);
                    TabMain.TabPages.Add(tab);
                }              
                TabMain.SelectedTabPage = tab;

                //Splitter.Panel2.Controls.Add(frame);
            }
            catch
            {
                SysMessage.Error("载入窗体失败");
            }
        }

        private void TabMain_CloseButtonClick(object sender, EventArgs e)
        {
            ClosePageButtonEventArgs arg = e as ClosePageButtonEventArgs;
            TabMain.TabPages.Remove(arg.Page as XtraTabPage);
        }

        private void WinMain_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                //Splitter.Panel2.ContentImageAlignement = System.Drawing.ContentAlignment.TopLeft;
                //Splitter.Panel2.ContentImage = System.Drawing.Image.FromFile("Image/背景.gif");

                //注册快捷键
                bool success = RegisterHotKey(Handle, 100, KeyModifiers.Alt, Keys.Oemtilde);
                if (!success)
                {
                    SysMessage.Error("注册快捷键出错");
                }
            }
        }

        private void WinMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.DesignMode)
            {
                //取消快捷键
                bool success = UnregisterHotKey(Handle, 100);
                if (!success)
                {
                    SysMessage.Error("取消快捷键出错");
                }
            }
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;

            switch (m.Msg)
            {
                case WM_HOTKEY:
                    if (ActiveForm == this)
                    {
                        WinKey winKey = new WinKey();
                        winKey.ShowDialog(this);
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,                // handle to window    
            int id,                     // hot key identifier    
            KeyModifiers fsModifiers,   // key-modifier options    
            Keys vk                     // virtual-key code    
        );

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,                // handle to window    
            int id                      // hot key identifier    
        );

        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

        private void btnExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }

        private void btnIdentifyIn_ItemClick(object sender, ItemClickEventArgs e)
        {
            WinIdentify win = new WinIdentify();
            if (win.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
        }

        private void btnIdentifyOut_ItemClick(object sender, ItemClickEventArgs e)
        {
            App.ResetCustomer();
           
            foreach(Control ctrl in Splitter.Panel2.Controls)
            {
                SysMenuItem menu = ctrl.Tag as SysMenuItem;
                if (menu.uiIdentify == "1")
                {
                    Splitter.Panel2.Controls.Remove(ctrl);
                }
            }         
        }
    }
}
